package com.jigsawapp.movies;

import android.app.Application;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.jigsawapp.movies.bean.User;
import com.jigsawapp.movies.common.StringUtils;

import java.util.Properties;
import java.util.UUID;

import static com.jigsawapp.movies.common.Contanst.ACCOUNT_EMAIL;
import static com.jigsawapp.movies.common.Contanst.ACCOUNT_PWD;
import static com.jigsawapp.movies.common.Contanst.PROP_KEY_UID;
import static com.jigsawapp.movies.common.Contanst.PROP_KEY_USERNAME;


/**
 * 全局类, 用于保存全局配置和网络数据
 * Created by jigsaw on 2016/3/9.
 * @version 1.0
 * @Email: fadeblack307@163.com
 */
public class AppContext extends Application {
    private boolean login = false;//登录状态
    private int loginUid = 0;//登录用户的id

    private static AppContext appContext;

    @Override
    public void onCreate() {
        super.onCreate();
        appContext = this;
    }

    public static AppContext getInstance() {
        return appContext;
    }

    public void setProperties(Properties ps) {
        AppConfig.getAppConfig(this).set(ps);
    }

    public Properties getProperties() {
        return AppConfig.getAppConfig(this).get();
    }

    public void setProperty(String key, String value) {
        AppConfig.getAppConfig(this).set(key, value);
    }

    public String getProperty(String key) {
        return AppConfig.getAppConfig(this).get(key);
    }

    public void removeProperty(String... key) {
        AppConfig.getAppConfig(this).remove(key);
    }

    /**
     * 保存用户的email和pwd
     */
    public void saveAccountInfo(String email, String pwd) {
        setProperty(ACCOUNT_EMAIL, email);
        setProperty(ACCOUNT_PWD, pwd);
    }


    public void saveLoginInfo(final User user) {
        if (null == user) {
            return;
        }
        // 保存用户的信息
        this.loginUid = user.getUid();
        this.login = true;
        setProperties(new Properties() {
            {
                setProperty(PROP_KEY_UID, String.valueOf(user.getUid()));
                setProperty(PROP_KEY_USERNAME, String.valueOf(user.getUsername()));
                setProperty(ACCOUNT_EMAIL, String.valueOf(user.getEmail()));
            }
        });
    }

    /**
     *获取APK安装包信息
     */
    public PackageInfo getPackageInfo() {
        PackageInfo info = null;

        try {
            info = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace(System.err);
        }
        if (info == null) {
            info = new PackageInfo();
        }
        return info;
    }

    /**
     * 获取App唯一标识
     */
    public String getAppId() {
        String uniqueID = getProperty(AppConfig.CONF_APP_UNIQUEID);
        if (StringUtils.isEmpty(uniqueID)) {
            uniqueID = UUID.randomUUID().toString();
            setProperty(AppConfig.CONF_APP_UNIQUEID, uniqueID);
        }
        return uniqueID;
    }

}
